package com.intexh.quickandroid.web.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.intexh.quickandroid.BuildConfig;
import com.intexh.quickandroid.R;
import com.intexh.quickandroid.base.BaseActivity;
import com.intexh.quickandroid.base.MainApplication;
import com.intexh.quickandroid.helper.UserHelper;
import com.intexh.quickandroid.net.Apis;
import com.intexh.quickandroid.net.NetworkManager;
import com.intexh.quickandroid.pay.PayHelper;
import com.intexh.quickandroid.pay.PayListener;
import com.intexh.quickandroid.pay.PaySuccessActivity;
import com.intexh.quickandroid.pay.event.WechatPayEvent;
import com.intexh.quickandroid.sharesdk.OneKeyShareHelper;
import com.intexh.quickandroid.sharesdk.bean.ShareBean;
import com.intexh.quickandroid.utils.DialogUtils;
import com.intexh.quickandroid.utils.GsonUtils;
import com.intexh.quickandroid.utils.LogCatUtil;
import com.intexh.quickandroid.web.inteface.JavaScriptInterface;
import com.intexh.quickandroid.web.manager.MyChromeClient;
import com.intexh.quickandroid.web.manager.WebViewClientUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WebViewActivity extends BaseActivity implements WebViewClientUtil.WebClientLoadListener, PayListener,
        MyChromeClient.ProgressChangedListener, MyChromeClient.ReceivedTitleListener {

    private static final String KEY_WEBURL = "KEY_WEBURL";
    public static final int BACK = 0x1fe;
    public static final int PAY = 0x2fe;
    public static final int SHARE = 0x3fe;
    public static final int LOGIN = 0x4fe;
    public static final int GO_HOME_USER = 0x5fe;

    //文件选择所需
    public final static int FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5 = 2;
    public final static int FILE_CHOOSER_RESULT_CODE = 1;// 表单的结果回调


    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.back_iv)
    ImageView backIv;
    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.refresh_tv)
    TextView refreshTv;
    @BindView(R.id.prograssBar)
    ProgressBar prograssBar;
    @BindView(R.id.refreshLayout)
    LinearLayout refreshLayout;
    private MyChromeClient myChromeClient;
    private String url;

    private Handler jsInterfaceHandler = new JsInterfaceHandler(this, this);
    private boolean actionWechatPay;

    /**
     * 不带参数的地址
     *
     * @param context
     * @param url
     */
    public static void startActivity(Context context, String url) {
        if (context == null) return;
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(KEY_WEBURL, url);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initWebView();
    }

    //同步cookie
    private void syncCookie(Context context, String url) {
        try {
            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeAllCookie();
            String oldCookie = cookieManager.getCookie(url);
            if (oldCookie != null) {
                LogCatUtil.d("Frank: webView.syncCookieOutter.oldCookie", oldCookie);
            }
            cookieManager.setCookie(url, "key=" + UserHelper.getCurrentToken());
            String newCookie = cookieManager.getCookie(url);
            if (newCookie != null) {
                LogCatUtil.d("Frank: webView.syncCookie.newCookie", newCookie);
            }
        } catch (Exception e) {
            LogCatUtil.e("Frank: webView.syncCookie failed", e.toString());
        }
    }


    private void initWebView() {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JavaScriptInterface(jsInterfaceHandler), "hzjs");
        webView.setWebViewClient(new WebViewClientUtil(this, this));
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setLoadsImagesAutomatically(true);// 加载网页中的图片
        webView.getSettings().setUseWideViewPort(true); //设置使用视图的宽端口
        webView.getSettings().setAllowFileAccess(true);// 可以读取文件缓存(manifest生效)
        webView.setWebChromeClient(myChromeClient = new MyChromeClient(this ,this, this));
        // webView.setDownloadListener(new MyDownloadStart(this));//设置下载监听
        // webview 从Lollipop(5.0)开始webview默认不允许混合模式，https当中不能加载http资源，需要设置开启
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        url = getIntent().getStringExtra(KEY_WEBURL);
//        if (UserHelper.isLogin() &&url.startsWith(BuildConfig.SERVERHEAD)) {
//            syncCookie(this, url);   //同步cookie
//        }
        loadUrl();
    }

    private void loadUrl() {
        //如果现在访问的地址在web界面集合中 关闭旧的界面
        if (MainApplication.webActivityList.containsKey(url)) {
            MainApplication.webActivityList.get(url).finish();
            MainApplication.removeActivity(url);
        }
        MainApplication.addActivity(url, this);
        //判断 如果url是完整地址 直接加载 不拼接 baseUrl
        if (url.startsWith("http")) {
            webView.loadUrl(url);
        } else {
            webView.loadUrl("http://" + url);
        }
        LogCatUtil.e("frank", "网页请求地址：" + url);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (MainApplication.webActivityList.containsKey(url)) {
            MainApplication.removeActivity(url);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        Uri result = intent == null || resultCode != RESULT_OK ? null: intent.getData();
        switch (requestCode){
            case FILE_CHOOSER_RESULT_CODE:
                if (null == myChromeClient.getmUploadMessage()) {
                    return;
                }
                myChromeClient.getmUploadMessage().onReceiveValue(result);
                myChromeClient.setmUploadMessage(null);
                break;
            case FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5:
                if (null == myChromeClient.getmUploadMessageForAndroid5())
                    return;
                if (result != null) {
                    myChromeClient.getmUploadMessageForAndroid5().onReceiveValue(new Uri[]{result});
                } else {
                    myChromeClient.getmUploadMessageForAndroid5().onReceiveValue(new Uri[]{});
                }
                myChromeClient.setmUploadMessageForAndroid5(null);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (webView.canGoBack() && event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    /*----------------------------------- 支付部分 ------------------------------------------*/
    public void actionWechatPay(){
        actionWechatPay =true;
    }
    /**
     * 微信支付状态监听
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(WechatPayEvent event) {
        if(!actionWechatPay){
            return; //没有吊起微信支付的界面 接收到微信支付消息终止执行此方法
        }
        LogCatUtil.e("frank", "微信支付消息：" + event.getPayStatus());
        switch (event.getPayStatus()) {
            case "ok":
                paySuccess("wechat");
                break;
            case "error":
                payFail("wechat", "支付失败，请重新支付");
                break;
            case "cancel":
                payFail("wechat", "支付取消");
                break;

        }

    }

    private String payType;
    private String orderId;
    @Override
    public void payStart(String payType,String orderId) {
        this.payType=payType;
        this.orderId=orderId;
        showProgress(true);
    }

    @Override
    public void payCancel(String payType) {
        hideProgress();
        DialogUtils.showHitDialog(mContext, "支付提示", "支付取消");
    }

    @Override
    public void paySuccess(String payType) {
        hideProgress();

        startActivity(PaySuccessActivity.class);
    }


    @Override
    public void payFail(String payType, String error) {
        hideProgress();
        DialogUtils.showHitDialog(mContext, "支付提示", error);
    }
    @Override
    public void loadFinished(String title,boolean isError) {
        if(isError){
            refreshLayout.setVisibility(View.VISIBLE);
            refreshTv.setVisibility(View.VISIBLE);
            prograssBar.setVisibility(View.GONE);
            webView.setVisibility(View.GONE);
        }else{
            webView.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.GONE);
        }
    }


    @OnClick({R.id.refresh_tv,R.id.back_iv})
    public void onViewClicked(View v) {
        switch (v.getId()){
            case R.id.back_iv:
                finish();
                break;
            case R.id.refresh_tv:
                webView.loadUrl(url);
                refreshTv.setVisibility(View.GONE);
                prograssBar.setVisibility(View.VISIBLE);
                break;
        }
    }

    /*--------------------------------H5 调用原生--------------------------------*/

    private static class JsInterfaceHandler extends Handler {
        private WeakReference<Activity> weakRefActivity;
        private WebViewActivity context;
        private PayListener payListener;

        public JsInterfaceHandler(WebViewActivity activity, PayListener payListener) {
            this.context = activity;
            this.payListener = payListener;
            weakRefActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            Activity activity = weakRefActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case BACK:
                        break;
                    case PAY:
                        String payInfo = (String) msg.obj;
                        String[] split = payInfo.split(",");
                        String paySn = split[0];
                        String orderId = split[1];
                        PayHelper.showPayTypeDialog(context, false, type -> {
                            if (type == PayHelper.ALI_PAY) {
                                aLiPay(paySn,orderId);
                            } else if (type == PayHelper.WECHAT_PAY) {
                                context.actionWechatPay();  //标识微信支付
                                wechatPay(paySn,orderId);
                            } else {

                            }
                        });
                        break;
                    case SHARE:
                        ShareBean shareBean = (ShareBean) msg.obj;
                        OneKeyShareHelper.INSTANCE.showShare(context, shareBean.getTitle(), shareBean.getText(), shareBean.getImageUrl(), shareBean.getLinkUrl());
                        break;
                    case LOGIN:
//                        UserHelper.loginOut();
//                        DialogUtils.showDefaultDialog(context,"提示","您账号在别处登录，请重新登录",new DialogUtils.DialogImpl(){
//                            @Override
//                            public void onOk() {
//                                Intent intent = new Intent(context,LoginActivity.class);
//                                context.startActivity(intent);
//                            }
//                        });
                        break;
                    case GO_HOME_USER:
                        break;
                }
            }
        }

        private void wechatPay(String s,String orderId) {
            Map<String, String> params = new HashMap<>();
            params.put("pay_sn", s);
            payListener.payStart("wechat",orderId);
            NetworkManager.INSTANCE.post(Apis.wechat_pay, params, new NetworkManager.OnRequestCallBack() {
                @Override
                public void onOk(String response) {
                    PayHelper.INSTANCE.weChatPay(context, response, payListener);
                }

                @Override
                public void onError(String errorMessage) {
                    payListener.payFail("wechat", errorMessage);
                }
            });
        }

        private void aLiPay(String s,String orderId) {
            Map<String, String> params = new HashMap<>();
            params.put("pay_sn", s);
            payListener.payStart("alipay",orderId);
            NetworkManager.INSTANCE.post(Apis.ali_pay, params, new NetworkManager.OnRequestCallBack() {
                @Override
                public void onOk(String response) {
                    PayHelper.INSTANCE.aliPay(context, GsonUtils.getStringFromJSON(response,"signStr"), payListener);
                }

                @Override
                public void onError(String errorMessage) {
                    payListener.payFail("alipay", errorMessage);
                }
            });
        }
    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        //进度显示
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        //网页加载完成 这里设置标题
        if (title.contains("http") || title.contains("网页无法打开") || title.contains(".com")||title.contains(".cn")) {
            return;
        }
        titleTv.setText(title);
    }


}
